# coding: utf-8

import numpy as np,cv2
import socket,struct,pickle
import json,time,sys,os, time

######################
#python client.py 183925
######################



# ADDR = ("10.55.130.29",9119)
ADDR = ("127.0.0.1",9119)
rootDir = "data"
if not os.path.exists(rootDir):
    os.mkdir(rootDir)

def sendData(client_conn,data):
    data_len = len(data)
    dataSize=4096
    count = data_len // dataSize
    for i in range(count):
        client_conn.send(   data[ i*dataSize : (i+1)*dataSize ]   )
    client_conn.send( data[count*dataSize:] )

def log(msg):
    print( "["+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"]",msg)

def runTest(depth_image,rgb):
    depth_image = depth_image / 10
    #######无效数据设置为0
    # depth_image = np.where( (depth_image>255)|(depth_image==0),255,depth_image )
    depth_image = np.where( (depth_image>255)|(depth_image==0),0,depth_image )
    depth_image = np.asarray(depth_image,dtype="uint8")
    # after_depth_image = cv2.cvtColor( depth_image,cv2.CV_8UC1 )
    _, imgencode = cv2.imencode('.jpeg',  rgb)
    # _, depthencode = cv2.imencode('.jpeg',  after_depth_image)
    _, depthencode = cv2.imencode('.jpeg',  depth_image)

    data_rgb = np.array(imgencode)
    data_depth = np.array(depthencode)

    stringData = data_rgb.tobytes()
    # depthStringData =  data_depth.tobytes()

    print( "rgb size:",len(stringData) )
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(ADDR)
    
    # sock.send( struct.pack(">LLii", len(stringData) , len(depthStringData), 0, 0 ) )
    ret = sock.send( struct.pack(">LLii", len(stringData) ,0, 0, 0 ) )
    print("send header:", ret)
    sendData(sock, stringData )
    # sendData(sock, depthStringData )
    log("send end")

    result = sock.recv(4096).decode()
    # print("recv data size:",len(result))
    if result:
        box_list = json.loads(result) 
        log("!!!!!!!!!!!!!!! raw data !!!!!!!!!!!!!!!!!! !!!!!!:")
        print( box_list  )
        log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        if box_list.__contains__("boxList"):
            return box_list["boxList"]
        else:
            return False

def readData(path):
    with open(path,"rb") as f:
        return f.read()

def main(argv):
    if len(argv) < 2:
        print("eq: python3 test.py 183925")
        print("if encouter error, please python2 test.py")
    else:
        begin = time.time()*1000
        print("time begin to read image:", begin)
        name = argv[1]
        rgb = os.path.join(rootDir,name+".rgb")
        d = os.path.join(rootDir,name+".d")
        log(rgb)
        log(d)
        if(  os.path.exists( rgb ) and os.path.exists( d )  ):
            runTest(  pickle.loads( readData(d) ),  pickle.loads( readData(rgb) ) )
        else:
            print("file not exist. please check")
        print("after send image: {} ms".format(time.time()* 1000 - begin))



if __name__ == "__main__":
    main(sys.argv)
    # test_list()
    
'''
[{'x': 709, 'y': 518, 'z': 0, 'rx': 0, 'ry': 0, 'rz': 0, 'conf': 0.839, 'cls': 0}, {'x': 444, 'y': 414, 'z': 0, 'rx': 0, 'ry': 0, 'rz': 0, 'conf': 0.825, 'cls': 0}, {'x': 629, 'y': 327, 'z': 0, 'rx': 0, 'ry': 0, 'rz': 0, 'conf': 0.817, 'cls': 0}, {'x': 757, 'y': 381, 'z': 0, 'rx': 0, 'ry': 0, 'rz': 0, 'conf': 0.881, 'cls': 1}, {'x': 493, 'y': 283, 'z': 0, 'rx': 0, 'ry': 0, 'rz': 0, 'conf': 0.878, 'cls': 1}, {'x': 575, 'y': 462, 'z': 0, 'rx': 0, 'ry': 0, 'rz': 0, 'conf': 0.874, 'cls': 1}]
'''
